#coding:utf-8
import json

import tornado.gen

from models import Dm as RawDm
from models import Room as RawRoom
import settings

current_dm_id = 0

dm_buffer = []

room = None

class Dm(RawDm):

    def __init__(self, *largs, **kwargs):
        global current_dm_id

        super(Dm, self).__init__(*largs, **kwargs)
        self._id = current_dm_id
        current_dm_id += 1
    
    @staticmethod
    def create(*largs, **kwargs):
        dm = Dm(*largs, **kwargs)
        dm.save()
        dm_buffer.append(dm)
        return dm

    @staticmethod
    @tornado.gen.coroutine
    def query(room_name, start_time):
        if room_name != room.name:
            return None
        result = []
        for dm in dm_buffer[::-1]:
            if dm.time <= start_time:
                break
            result.append(dm)
        return result

    def save(self):
        with open(settings.DM_FILE, "a") as dm_file:
            dm_file.write(json.dumps(self.dict()))
            dm_file.write("\n")

class Room(RawRoom):

    def __init__(self, name = None, password = None):
        if room is not None:
            raise Exception("Cannot create more than one room when settings.STORAGE equals \"file\"")
        with open(settings.ROOM_CONFIG_FILE, "r") as config_file:
            try:
                config = json.loads(config_file.read())
            except TypeError:
                raise Exception("Room config file format error")

            self._name = config["name"]
            self._password = config["password"]
            self._config = config["config"]

    @staticmethod
    def query(name):
        if room is None:
            return None
        
        if room.name == name:
            return room

        return None

    @staticmethod
    def create(**kwargs):
        raise NotImplementedError

    def save(self):
        with open(settings.ROOM_CONFIG_FILE, "w") as config_file:
            config_file.write(json.dumps(self.dict()))

room = Room()

if __name__ == "__main__":
    print(room.dict())
    room.config["hhh"] = "hhh"
    room.save()
    dm = Dm.create("test dm")
    print(dm.dict())

